package org.phone.web.controller;

import java.util.List;
import java.util.Set;

import org.phone.manager.entity.ProductType;
import org.phone.manager.services.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/category")
public class CategoryController extends ParentController {

	@Autowired
	@Qualifier("categoryService")
	private CategoryService cs;

	@RequestMapping(method = RequestMethod.GET)
	public String showCategory(Model model) {
		List<List> typeNamelist = cs.getAllTypeName();
		model.addAttribute("productType", new ProductType());
		model.addAttribute("typeNamelist", typeNamelist);
		return "category";
	}

	@RequestMapping(value = "/delType", method = RequestMethod.GET, params = "id")
	public String deleteCategory(@RequestParam("id") Integer id) {
		ProductType typePrepareDelete = (ProductType) cs.getEntity(ProductType.class, id);
		cs.deleteEntity(typePrepareDelete);
		return "redirect:/category";
	}

	@RequestMapping(value = "/addtype", method = RequestMethod.GET)
	public String showAddType(@RequestParam("id") Integer id, Model model) {
		ProductType parentType = (ProductType) cs.getEntity(ProductType.class, id);
		ProductType childrenType = new ProductType();
		model.addAttribute("childrenType", childrenType);
		model.addAttribute("parentType", parentType);
		return "addtype";
	}

	@RequestMapping(value = "/updatetype", method = RequestMethod.GET)
	public String showEditType(@RequestParam("id") Integer id, Model model) {
		ProductType childrenType = (ProductType) cs.getEntity(ProductType.class, id);
		ProductType parentType = childrenType.getParentType();
		model.addAttribute("childrenType", childrenType);
		model.addAttribute("parentType", parentType);
		return "addtype";
	}

	@RequestMapping(value = "/saveOrUpdatetype",method = RequestMethod.POST)
	public String addType(ProductType childrenType, @RequestParam("num") Integer id) {
		ProductType parentType = (ProductType) cs.getEntity(ProductType.class, id);
		childrenType.setParentType(parentType);
		cs.saveOrUpdateEntity(childrenType);
		return "redirect:/category";
	}

	@RequestMapping(value = "/creatType",method = RequestMethod.POST)
	public String creatType(ProductType productType) {
		productType.setParentType(productType);
		cs.saveEntity(productType);
		return "redirect:/category";
	}
	
	
}
